<template>
  <div class="role-container">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form layout="inline" :model="queryParams" @finish="handleQuery" class="search-form">
        <a-form-item label="角色名称" name="roleName">
          <a-input v-model:value="queryParams.roleName" placeholder="请输入角色名称" />
        </a-form-item>
        <a-form-item label="角色标识" name="roleKey">
          <a-input v-model:value="queryParams.roleKey" placeholder="请输入角色标识" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="queryParams.status" placeholder="请选择状态" style="width: 120px">
            <a-select-option :value="null">全部</a-select-option>
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              <template #icon><search-outlined /></template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon><redo-outlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
      
      <!-- 操作按钮 -->
      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd" v-if="hasPermission('system:role:add')">
            <template #icon><plus-outlined /></template>
            新增
          </a-button>
          <a-button type="primary" danger :disabled="!selectedRowKeys.length" @click="handleBatchDelete"
            v-if="hasPermission('system:role:delete')">
            <template #icon><delete-outlined /></template>
            批量删除
          </a-button>
        </a-space>
      </div>
      
      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data-source="roleList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :row-key="(record: any) => record.roleId"
        @change="handleTableChange"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'success' : 'error'">
              {{ record.status === 1 ? '正常' : '禁用' }}
            </a-tag>
          </template>
          
          <!-- 操作列 -->
          <template v-if="column.key === 'operation'">
            <a-space>
              <a @click="handleEdit(record)" v-if="hasPermission('system:role:edit')">编辑</a>
              <a-divider type="vertical" />
              <a @click="handlePermission(record)" v-if="hasPermission('system:role:permission')">权限分配</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这个角色吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
                v-if="hasPermission('system:role:delete')"
              >
                <a class="danger-text">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 角色表单对话框 -->
    <role-form
      v-model:visible="formVisible"
      :form-data="formData"
      @success="handleSuccess"
    />
    
    <!-- 权限分配对话框 -->
    <role-permission
      v-model:visible="permissionVisible"
      :role-id="currentRoleId"
      @success="handlePermissionSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import * as roleApi from '@/api/role'
import { usePermission } from '@/composables/usePermission'
import type { SysRole } from '@/types/role'
import type { TableProps } from 'ant-design-vue'
import RoleForm from './components/RoleForm.vue'
import RolePermission from './components/RolePermission.vue'

// 权限检查
const { checkPermission: hasPermission } = usePermission()

// 状态
const loading = ref(false)
const roleList = ref<SysRole[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

// 查询参数
const queryParams = reactive({
  roleName: '',
  roleKey: '',
  status: null
})

// 选中行数据
const selectedRowKeys = ref<(string | number)[]>([])

// 表单状态
const formVisible = ref(false)
const formData = ref<Partial<SysRole>>({})

// 权限分配状态
const permissionVisible = ref(false)
const currentRoleId = ref<number>()

// 表格列定义
const columns = [
  {
    title: '角色ID',
    dataIndex: 'roleId',
    key: 'roleId',
    width: 80
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
    key: 'roleName'
  },
  {
    title: '角色标识',
    dataIndex: 'roleKey',
    key: 'roleKey'
  },
  {
    title: '排序',
    dataIndex: 'roleSort',
    key: 'roleSort'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    sorter: true
  },
  {
    title: '操作',
    key: 'operation',
    width: 200
  }
]

// 初始化
onMounted(() => {
  getList()
})

// 获取角色列表
const getList = async () => {
  loading.value = true
  try {
    const params: any = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    }
    
    // 只添加非空和非null的查询参数
    if (queryParams.roleName) {
      params.roleName = queryParams.roleName
    }
    if (queryParams.roleKey) {
      params.roleKey = queryParams.roleKey
    }
    if (queryParams.status !== null && queryParams.status !== undefined) {
      params.status = queryParams.status
    }
    
    const res = await roleApi.getRolePage(params)
    
    if (res) {
      roleList.value = res.rows || []
      pagination.total = res.total || 0
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.current = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.roleName = ''
  queryParams.roleKey = ''
  queryParams.status = null
  pagination.current = 1
  getList()
}

// 表格变化处理
const handleTableChange: TableProps['onChange'] = (pag, filters, sorter) => {
  pagination.current = pag.current as number
  pagination.pageSize = pag.pageSize as number
  getList()
}

// 选择行变化
const onSelectChange = (keys: (string | number)[]) => {
  selectedRowKeys.value = keys
}

// 新增角色
const handleAdd = () => {
  formData.value = {
    status: 1, // 设置为正常状态(1)
    roleSort: 0
  }
  formVisible.value = true
}

// 编辑角色
const handleEdit = (record: SysRole) => {
  formData.value = { ...record }
  formVisible.value = true
}

// 删除角色
const handleDelete = async (record: SysRole) => {
  try {
    await roleApi.deleteRole(record.roleId)
    message.success('删除成功')
    if (pagination.current === 1) {
      getList()
    } else {
      pagination.current = 1
      getList()
    }
  } catch (error) {
    console.error('删除角色失败:', error)
    message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRowKeys.value.length) {
    message.warning('请至少选择一条记录')
    return
  }
  
  message.info('批量删除角色功能待实现')
}

// 权限分配
const handlePermission = (record: SysRole) => {
  currentRoleId.value = record.roleId
  permissionVisible.value = true
}

// 表单提交成功回调
const handleSuccess = () => {
  formVisible.value = false
  getList()
}

// 权限分配成功回调
const handlePermissionSuccess = () => {
  permissionVisible.value = false
  getList()
}
</script>

<style scoped>
.role-container {
  padding: 24px;
}

.search-form {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 16px;
}

.danger-text {
  color: #ff4d4f;
}

.danger-text:hover {
  color: #ff7875;
}
</style>
